<template>
  <div class="list-container">
    <van-tabs v-model="queryObj.sort" @change="tabChange">
      <van-tab title="默认排序" name></van-tab>
      <van-tab title="销量优先" name="1"></van-tab>
      <van-tab title="价格优先" name="4"></van-tab>
    </van-tabs>
    <div class="main-container">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="main-item" v-for="(item, index) in List" :key="index" @click="details(item)">
          <div class="left-container">
            <img :src="imgUrl + item.indexpic" alt />
          </div>
          <div class="right-container">
            <div class="name">
              {{ item.title }}
            </div>
            <div class="num">已售 {{ item.sold + item.soldinit }}</div>
            <div class="footer">
              <div class="price">$ {{item.price}}</div>
              <div class="btn" @click.stop="addCollage(item)" v-if="type === 'collage'">加入拼团</div>
              <div class="btn" @click.stop="addCart(item)" v-else>加入购物车</div>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 商品规格 -->
    <van-sku
      ref="sku"
      v-model="cartShow"
      :sku="sku"
      :show-add-cart-btn="false"
      buy-text="加入购物车"
      :goods="goodDetails"
      :goods-id="goodDetails.id"
      :hide-stock="goodDetails.hide_stock"
      @buy-clicked="onAddCard"
    >
      <div slot="sku-header-price" style="color:#ee0a24" class="van-sku__goods-price">
        <span class="van-sku__price-symbol">$ </span>
        <span class="van-sku__price-num">{{ sku.price }}</span>
      </div>
    </van-sku>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      finished: false,
      type: null,
      urls: {
        search: "/home/item/search", // 搜索
        collage: "/home/lists/flashgroup", // 国际拼团
        rushToBuy: "/home/lists/flashsale", // 限时抢购
        newProducts: "/home/lists/newpro" // 新品上架
      },
      active: 0,
      queryObj: {
        sort: "",
        p: 1
      },
      total: 0,
      List: [],
      cartShow: false,
      goodDetails: {
        picture: null
      },
      sku: {
        // // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [],
        // // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [],
        price: 0, // 默认价格（单位元）
        stock_num: 0, // 商品总库存
        collection_id: null, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: true, // 是否无规格商品
        hide_stock: true // 是否隐藏剩余库存
      }
    };
  },
  computed: {
    imgUrl() {
      return this.$imgUrl;
    },
    userInfo() {
      return this.$store.state.userData;
    }
  },
  created() {
    this.type = this.$route.query.type;
    this.getList();
  },
  methods: {
    onLoad() {
      this.queryObj.p++;
      this.getList();
    },
    async getList() {
      let params = JSON.parse(JSON.stringify(this.queryObj));
      if (this.type === "search") {
        params.keyword = this.$route.query.val;
      }
      this.loading = true;
      const result = await this.$fetchGet(this.urls[this.type], params);
      this.loading = false;
      const obj = {
        search: "list",
        collage: "flashgroup",
        rushToBuy: "flashsale",
        newProducts: "newproduct"
      };
      this.total = result.data[obj[this.type]].total;
      this.List = [...this.List, ...result.data[obj[this.type]].data];
      if (this.List.length >= this.total) {
        this.finished = true;
      }
    },
    tabChange(name, title) {
      this.finished = false;
      this.queryObj.p = 1;
      this.List.length = 0;
      this.getList();
    },
    addCollage (item) {
      this.$router.push({
        path: '/shopping/details',
        query: {
          type: 'figview',
          id: item.id
        }
      })
    },
    details(item) {
      let obj = {
        search: "new", // 搜索
        collage: "figview", // 国际拼团
        rushToBuy: "actview", // 限时抢购
        newProducts: "new" // 新品上架
      };
      this.$router.push({
        path: '/shopping/details',
        query: {
          type: obj[this.type],
          id: item.id
        }
      })
      console.log(item);
    },
    addCart (item) {
      this.goodDetails.picture = this.imgUrl + item.indexpic
      this.sku.price = item.price
      this.sku.collection_id = item.id
      this.sku.stock_num = item.stock
      this.cartShow = true
    },
    async onAddCard (e) {
      if (!this.userInfo) {
        this.$dialog.alert({
          title: '温馨提示',
          message: '请先登录',
        }).then(() => {
          // on close
        });
        return
      }
      const result = await this.$fetchGet('/home/cart/add', {
        productid: e.selectedSkuComb.id,
        num: e.selectedNum
      })
      if (!result.success) {
        this.$toast(result.msg)
        return
      }
      this.cartShow = false
      this.$store.commit('changeCartList')
      this.$toast('加入购物车成功')
    }
  }
};
</script>

<style lang="scss">
.list-container {
  .main-container {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    background: #ffffff;
    .main-item {
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      border-bottom: 1px solid #d8d8d8;
      .left-container {
        img {
          width: 200px;
          height: 200px;
        }
      }
      .right-container {
        flex: 1;
        margin-left: 50px;
        display: flex;
        flex-direction: column;
        .name {
          font-size: 30px;
          font-weight: 500;
          flex: 1;
        }
        .num {
          color: #929292;
          font-size: 25px;
          margin-bottom: 5px;
        }
        .footer {
          display: flex;
          .price {
            font-size: 30px;
            font-weight: bold;
            color: #ff3b3b;
            flex: 1;
          }
          .btn {
            width: 180px;
            height: 60px;
            color: #fff;
            font-weight: bold;
            border-radius: 60px;
            text-align: center;
            line-height: 60px;
            background: linear-gradient(to right, #fc8f04, #f71c19);
          }
        }
      }
    }
  }
}
</style>